<template>
<div id="app-save">
    <el-card shadow="always">
  <el-form ref="form" :model="student" label-width="80px">
    <el-form-item label="学生姓名">
      <el-input v-model="student.sname"></el-input>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="student.sex">
        <el-radio label="男" >男</el-radio>
        <el-radio label="女" >女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="住址">
      <el-input v-model="student.addr"></el-input>
    </el-form-item>
    <el-form-item label="班级">
      <el-select v-model="student.cid" placeholder="请选择班级">
        <el-option v-for="c in clasList" :label="c.cname" :value="c.cid" :key="c.cid"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveStudent">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
  </el-card>
  </div>
</template>
<script>
import stuApi from "@/api/student/student";
import clasApi from "@/api/student/classes";

export default {
  data() {
    return {
      student: {},
      clasList: [],
    };
  },

  created() {
    this.findAllClasses()
    let sid = this.$route.query.sid;
    if (sid) {
      this.student.sid = sid;
      this.findStudent(sid)
    }
  },

  methods: {
    findStudent(sid) {
        stuApi.findStudentById(sid).then(resp => {
            this.student = resp.data.stu;
        })
    },

    //查询所有班级
    findAllClasses() {
      clasApi.getAllClasses().then((resp) => {
        this.clasList = resp.data.list;
      });
    },

    //取消
    cancel() {
      this.$router.push("/student/list");
    },

    saveStudent() {
      if (this.student.sid) {
        //有id为修改操作
        this.updateStudent();
      } else {
        this.addStudent();
      }
    },

    //修改学生
    updateStudent() {
      stuApi.updateStudent(this.student).then((resp) => {
        if (resp.code == 0) {
          this.$message({
            message: resp.message,
            type: "success",
          });
        }

        this.$router.push("/student/list");
      });
    },

    //添加学生
    addStudent() {
      stuApi.addStudent(this.student).then((resp) => {
        if (resp.code == 0) {
          this.$message({
            message: resp.message,
            type: "success",
          });
        }

        this.$router.push("/student/list");
      });
    },
  },
}
</script>

<style>
    #app-save{
        width: 800px;
        margin: 100px auto;
    }

</style>